/**
 * Created by alexander.persson on 2013-12-19.
 */

var CalandarV;

(function(){

    'use strict';

    var CalendarView = Backbone.View.extend({

        initialize: function() {
            this.model = new Cm(this.ourUrl);
            this.model.on('sync', this.fetchedModel, this);
            this.model.on('error', function(e) {

            }, this);
            var self = this;
            setInterval(function(){
                self.model.fetch();

            }, 60000);
            this.model.fetch();
            this.meetingRoom = null;
            var self = this;
            setInterval(function() {
                self.renderNow(self.entries);
            }, 1000);
        },

        fetchedModel: function() {
            this.entries = [];
            var self = this;
            this.meetingRoom = this.model.get('feed').title.$t;
            this.$el.find('.meeting-room').html(this.meetingRoom);

            _.each(this.model.get('feed').entry, function(entry){

                    //console.log(entry.summary.$t);
                    var date, start, end;
                    if(entry.summary.$t.slice(9, 14) === 'ing;n'){
                        // MÅNDAG
                        date = entry.summary.$t.slice(15, 25);
                        start = entry.summary.$t.slice(26, 31);
                        end = entry.summary.$t.slice(37, 42);


                    } else if(entry.summary.$t.slice(9, 13) === 'ml;r'){
                        //LÖRDAG
                        date = entry.summary.$t.slice(14, 24);
                        start = entry.summary.$t.slice(25, 30);
                        end = entry.summary.$t.slice(36, 41);

                    } else if(entry.summary.$t.slice(9, 13) === 'ml;n'){
                        // SÖNDAG
                        date = entry.summary.$t.slice(14, 24);
                        start = entry.summary.$t.slice(25, 30);
                        end = entry.summary.$t.slice(36, 41);


                    } else {
                        // ÖVRIGA
                        date = entry.summary.$t.slice(9, 19);
                        start = entry.summary.$t.slice(20, 25);
                        end = entry.summary.$t.slice(31, 36);
                    }

                    //Kolla om det är en gammal entry

                    var entryDate = self.formatDate(date, end);//new Date(date + "-" + end);
                    var nowDate = new Date();
                    if(entryDate < nowDate) {
                        return;
                    }

                    // Lägg till i array
                    var day = new Date(date).getDay();

                    switch(day)
                    {
                        case 0:
                            day = 'Söndag';
                            break;
                        case 1:
                            day = 'Måndag';
                            break;
                        case 2:
                            day = 'Tisdag';
                            break;
                        case 3:
                            day = 'Onsdag';
                            break;
                        case 4:
                            day = 'Torsdag';
                            break;
                        case 5:
                            day = 'Fredag';
                            break;
                        case 6:
                            day = 'Lördag';
                            break;

                    }

                    self.entries.push({date: date, start: start, end: end, day: day});
                });


            //this.entries.reverse();
            this.renderNow();
            this.renderAllEntries();
        },

        formatDate: function(date, time) {
            var year, month, days, hours, minutes;

            year = date.slice(0, 4);
            month = parseInt(date.slice(5, 7)) - 1;
            days = date.slice(8, 10);
            hours = time.slice(0, 2);
            minutes = time.slice(3, 5);

            return new Date(year, month, days, hours, minutes);
        },

        renderNow: function() {
            if(!this.entries) { return; }

            var div = this.$el.find(".now");
            if(this.entries.length === 0) {
                div.css("background-color", '#2AA876');
                $(div).find("h3").text("Rummet är ledigt");
                return;
            }

            var lastEntryDate = this.formatDate(this.entries[0].date, this.entries[0].end);//new Date(this.entries[0].date + " " + this.entries[0].end);
            var entryDate;
            var nowDate = new Date();
            var infoText;

            //var firstEntryDateEndTime = new Date(this.entries[0].date + " " + this.entries[0].end)
            var firstEntryDateStartTime = this.formatDate(this.entries[0].date, this.entries[0].start);//new Date(this.entries[0].date + " " + this.entries[0].start);
            var difference;

            var difference, hours, minutes, seconds;

            //if(firstEntryDateEndTime > nowDate) {
            if(firstEntryDateStartTime < nowDate) {
                //Room is not available
                for (var i=1; i < this.entries.length; i+= 1) {
                    entryDate = this.formatDate(this.entries[i].date, this.entries[i].start)//new Date(this.entries[i].date + " " + this.entries[i].start);
                    if(entryDate > lastEntryDate) {
                        //Då finns det en lucka!!!!
                        break;
                    }
                    lastEntryDate = this.formatDate(this.entries[i].date, this.entries[i].end);//new Date(this.entries[i].date + " " + this.entries[i].end);;
                }

                difference = lastEntryDate - nowDate;
                difference = this.calcutlateTime(difference);


                infoText = "Ledigt om ";
                if(difference.days > 0) {
                    infoText += difference.days + "d ";
                } if(difference.hours > 0) {
                    infoText += difference.hours + "h ";
                } if (difference.minutes > 0) {
                    infoText += difference.minutes + "m ";
                } if(difference.seconds > 0) {
                    infoText += difference.seconds + "s";
                }

                div.css("background-color", '#CE4D45');
            }
            else {
                //Room is available
                var firstEntryDate = this.formatDate(this.entries[0].date, this.entries[0].start);//new Date(this.entries[0].date + " " + this.entries[0].start);
                var nowDate = new Date();
                difference = firstEntryDate - nowDate;
                difference = this.calcutlateTime(difference);
                infoText = "Ledigt i ";
                if(difference.days > 0) {
                    infoText += difference.days + "d ";
                }if(difference.hours > 0) {
                    infoText += difference.hours + "h ";
                } if (difference.minutes > 0) {
                    infoText += difference.minutes + "m ";
                } if (difference.seconds > 0) {
                    infoText += difference.seconds + "s ";
                }

                div.css("background-color", '#2AA876');
            }
            //}

            $(div).find("h3").text(infoText);
        },

        /*calcutlateTime: function(difference) {
            var hours = Math.floor(difference / 36e5);
            var minutes = Math.floor(difference % 36e5 / 60000);
            var seconds = Math.floor(difference % 60000 / 1000);
            return {hours: hours, minutes: minutes, seconds: seconds};

        },*/

        calcutlateTime: function( difference ) {
            difference = difference/1000;
            var seconds = Math.floor(difference % 60);
            difference = difference/60;
            var minutes = Math.floor(difference % 60);
            difference = difference/60;
            var hours = Math.floor(difference % 24);
            var days = Math.floor(difference /24);

            return {days: days, hours: hours, minutes: minutes, seconds: seconds};
        },

        renderAllEntries: function() {
            if(!this.entries || this.entries.length === 0) { return; }
            var div = this.$el.find('.all-entries');
            var ul = $(div).find('ul');
            ul.html('');
            var self = this;
            var isNewDay = true;
            var prevDate = null;
            var entryUl = null;

            _.each(this.entries, function(entry, index){

                if(prevDate === entry.date ){
                    isNewDay = false;
                } else {
                    isNewDay = true;
                }
                // Gör LI-element -> appenda in p taggar -> appenda in Li-elemnetet i ul

                if(isNewDay){
                    var li = '<li class="new-day">' + '<span class="day">' + entry.day + '</span>' + '<span class="date">' + entry.date + '</span>' + '<ul class="meetings entry-ul-' + index + '"></ul>' + '</li>';
                    prevDate = entry.date;

                    $(ul).append(li);
                    entryUl = $(this.el).find('.entry-ul-' + index);

                }


                var  entryLi = '<li><div class="klockslag">' +
                    '<span class="start">' + entry.start + ' - </span>'+
                    '<span class="end">' + entry.end + '</span>'+
                    '</div></li>';
                $(entryUl).append(entryLi);



                // För varje ny dal vill jag ha en ny li med  ul

            }, this);
        }

    });
    CalandarV = CalendarView;

}());


var generateUrl = function(id) {
return 'http://www.google.com/calendar/feeds/' + id + '/public/basic?alt=json-in-script&callback=?&orderby=starttime&max-results=15&singleevents=true&sortorder=ascending&futureevents=true&ctz=Europe/Stockholm';
}

